<template>
    <el-row class="login-container">
      <el-card>
        <template #header>
          <div class="card-header">
            <img :src="imgUrl" alt="logo" />
          </div>
        </template>
        <div class="jump-link">
          <el-link @click="handleChange">{{ formType ? '返回登录' : '注册账号' }}</el-link>
        </div>
  
        <el-form :model="loginForm" style="max-width: 600px">
          <el-form-item prop="userName">
            <el-input v-model="loginForm.userName" placeholder="手机号" prefix-icon="User"></el-input>
          </el-form-item>
          <el-form-item v-if="formType" prop="passWordConfirm">
            <el-input v-model="loginForm.passWordConfirm" placeholder="确认密码" prefix-icon="Lock"></el-input>
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input v-model="loginForm.passWord" placeholder="密码" prefix-icon="Lock"></el-input>
          </el-form-item>
          <el-form-item prop="validCode" v-if="!formType">
            <el-input v-model="loginForm.validCode" placeholder="验证码">
              <template #append>
                <el-button @click="countdownChange">{{ countdown.validText }}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">
              {{ formType ? '注册' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>
  </template>
  
  <script setup>
  import { ref, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import axios from 'axios';
  
  const router = useRouter();
  
  const imgUrl = new URL("../../public/dali.jpg", import.meta.url).href;
  
  // 表单数据
  const loginForm = reactive({
    userName: '',
    passWord: '',
    passWordConfirm: '',
    validCode: ''
  });
  
  // 表单类型切换 (0: 登录, 1: 注册)
  const formType = ref(0);
  
  // 切换登录和注册
  const handleChange = () => {
    formType.value = formType.value ? 0 : 1;
    loginForm.userName = '';
    loginForm.passWord = '';
    loginForm.passWordConfirm = '';
    loginForm.validCode = '';
  };
  
  // 倒计时功能
  const countdown = reactive({
    validText: '获取验证码',
    time: 60,
    code: ''
  });
  
  let flag = false;
  let timer = null;
  
  const countdownChange = () => {
    if (flag) return;
  
    if (!loginForm.userName) {
      ElMessage({ message: '请填写手机号', type: 'warning' });
      return;
    }
  
    countdown.code = Math.floor(100000 + Math.random() * 900000).toString();
    console.log('模拟验证码:', countdown.code);
  
    flag = true;
    countdown.validText = `剩余${countdown.time}s`;
  
    timer = setInterval(() => {
      if (countdown.time <= 0) {
        clearInterval(timer);
        countdown.time = 60;
        countdown.validText = '获取验证码';
        flag = false;
      } else {
        countdown.time -= 1;
        countdown.validText = `剩余${countdown.time}s`;
      }
    }, 1000);
  };
  // 提交表单
// 提交表单
const handleSubmit = () => {
  if (formType.value === 1) {
    // 注册逻辑
    if (!loginForm.userName || !loginForm.passWord || !loginForm.passWordConfirm) {
      ElMessage({ message: '请填写完整信息', type: 'warning' });
      return;
    }

    if (loginForm.passWord !== loginForm.passWordConfirm) {
      ElMessage({ message: '两次输入密码不一致', type: 'error' });
      return;
    }

    axios.post('/api/register', {
      userName: loginForm.userName,
      passWord: loginForm.passWord
    }).then(response => {
      if (response.data.success) {
        ElMessage({ message: '注册成功', type: 'success' });
        handleChange();
      } else {
        ElMessage({ message: response.data.message, type: 'error' });
      }
    }).catch(error => {
      console.error('注册失败:', error);
      ElMessage({ message: '注册失败', type: 'error' });
    });
  } else {
    // 登录逻辑
    if (!loginForm.userName || !loginForm.passWord) {
      ElMessage({ message: '请填写完整信息', type: 'warning' });
      return;
    }

    axios.post('/api/login', {
      userName: loginForm.userName,
      passWord: loginForm.passWord
    }).then(response => {
      if (response.data.success) {
        // 存储 token
        localStorage.setItem('token', response.data.data.token);
        ElMessage({ message: '登录成功', type: 'success' });
        router.push('/dashboard');
      } else {
        ElMessage({ message: response.data.message, type: 'error' });
      }
    }).catch(error => {
      console.error('登录失败:', error);
      ElMessage({ message: '登录失败', type: 'error' });
    });
  }
};
  </script>
  
  <style lang="less" scoped>
  :deep(.el-card__header) {
    padding: 0;
  }
  
  .login-container {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  
    .card-header {
      img {
        width: 430px;
      }
    }
  
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }
  </style>